from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.db import transaction
from .models import TestSuite, TestCase, TestExecution, TestReport
from .serializers import (
    TestSuiteSerializer, TestCaseSerializer,
    TestExecutionSerializer, TestReportSerializer
)


class TestSuiteViewSet(viewsets.ModelViewSet):
    queryset = TestSuite.objects.all()
    serializer_class = TestSuiteSerializer

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

    @action(detail=True, methods=['get'])
    def test_cases(self, request, pk=None):
        """获取套件下的所有测试用例"""
        suite = self.get_object()
        test_cases = suite.testcase_set.all()
        serializer = TestCaseSerializer(test_cases, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def execute(self, request, pk=None):
        """执行测试套件"""
        suite = self.get_object()

        # 创建执行记录
        execution = TestExecution.objects.create(
            suite=suite,
            created_by=request.user,
            total_cases=suite.testcase_set.count()
        )

        # 这里可以调用你的测试执行引擎
        # 暂时模拟执行
        execution.status = 'success'
        execution.passed_cases = suite.testcase_set.count()
        execution.failed_cases = 0
        execution.execution_log = f"测试套件 {suite.name} 执行完成"
        execution.save()

        # 生成报告
        report = TestReport.objects.create(
            execution=execution,
            summary=f"测试套件 {suite.name} 执行报告",
            report_data={
                'total_cases': execution.total_cases,
                'passed_cases': execution.passed_cases,
                'failed_cases': execution.failed_cases,
                'success_rate': 100.0 if execution.total_cases > 0 else 0
            }
        )

        execution_serializer = TestExecutionSerializer(execution)
        return Response(execution_serializer.data)


class TestCaseViewSet(viewsets.ModelViewSet):
    queryset = TestCase.objects.all()
    serializer_class = TestCaseSerializer

    def get_queryset(self):
        queryset = TestCase.objects.all()
        suite_id = self.request.query_params.get('suite_id')
        if suite_id:
            queryset = queryset.filter(suite_id=suite_id)
        return queryset


class TestExecutionViewSet(viewsets.ModelViewSet):
    queryset = TestExecution.objects.all()
    serializer_class = TestExecutionSerializer

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

    @action(detail=True, methods=['get'])
    def report(self, request, pk=None):
        """获取执行报告"""
        execution = self.get_object()
        try:
            report = execution.testreport
            serializer = TestReportSerializer(report)
            return Response(serializer.data)
        except TestReport.DoesNotExist:
            return Response(
                {'detail': '报告尚未生成'},
                status=status.HTTP_404_NOT_FOUND
            )


class TestReportViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = TestReport.objects.all()
    serializer_class = TestReportSerializer